# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from ..zncspt_api.odoo_zncspt import OdooApi
from ..zncspt_api.zncspt import access_token


import datetime


import logging

_logger = logging.getLogger(__name__)


ONE_HOUR = 3600


def access_token_check(company_config_id):
    config = company_config_id
    last = config.lasttime
    expires_in = config.expires_in
    now = datetime.datetime.now()
    token = config.access_token

    if token and last and expires_in:
        if (now - last).total_seconds() < (expires_in - ONE_HOUR):
            return

    req_url = config.check_provider_id.endpoint

    appkey = config.appkey
    app_secret = config.app_secret

    res = access_token(req_url, appkey, app_secret)

    return res


def api_get(fapiao_check):
    company = fapiao_check.company_id
    company_config = company.env['fp.company.zncspt'].search(
        [('company_id', '=', company.id)], limit=1)

    company_config.access_token_check()
    req_url = fapiao_check.check_provider_id.endpoint

    appkey = company_config.appkey
    app_secret = company_config.app_secret
    token = company_config.access_token
    tin = company_config.tin

    api = OdooApi(req_url, appkey, app_secret, token, tin)
    return api


def check_fapiao(fapiao_check):
    print('12345678890', 'check_fapiao', )

    result = []
    for one in fapiao_check:
        record = _api_check_fapiao(one)
        record2 = record.copy()
        record2['id'] = one.id
        result.append(record2)

    return result


def _api_check_fapiao(fapiao_check):

    fapiao = fapiao_check.fapiao_id

    check_code = fapiao.check_code  # last 6bit, '110881'

    amount_total = fapiao.amount_total
    type_code = fapiao.type_code
    code = fapiao.code

    date_fapiao = fapiao.date_fapiao  # yyyymmdd
    date_fapiao = date_fapiao.strftime('%Y%m%d')

    invoice_type = fapiao.invoice_type

    values = {
        'check_code': check_code,
        'amount_total': amount_total,
        'type_code': type_code,
        'code': code,
        'date_fapiao': date_fapiao,
        'invoice_type': invoice_type,
    }

    api = api_get(fapiao_check)

    response = api.check_one(values)
    _logger.info('check fapiao...response:%s,', response)

    # print('test ok', response)

    error = response.get('error')
    if error:
        # print('error', response)
        # return
        raise ValueError("check fapiao error for %s: %r" % (fapiao, response))

    result = response.get('result')
    if not result:
        # print('error', response)
        # return
        raise ValueError("check fapiao error for %s: %r" % (fapiao, response))

    now = datetime.datetime.now()
    api_check_date = now.strftime('%Y-%m-%d')
    result['api_check_date'] = api_check_date

    return result
